//
//  QDBookDoctorController.m
//  simulateQuickDoctor
//
//  Created by 梁家伟 on 17/3/23.
//  Copyright © 2017年 PipiXia. All rights reserved.
//

#import "QDBookDoctorController.h"
#import "QDBookDoctorRadioCell.h"
#import "QDBookDoctorNormalCell.h"
#import "QDSelectSicknessController.h"
#import "QDSelectDiagnosisController.h"
#import "QDDoctorApplyController.h"
#import "QDSelectComlicationController.h"
#import "QDBannerTools.h"
#import "QDNetworkTool.h"

//静态cell的类型
typedef enum : NSUInteger {
    QDBookDoctorCellTypeSickness,
    QDBookDoctorCellTypeComplication,
    QDBookDoctorCellTypeIsConfirmed,
    QDBookDoctorCellTypeHasDiagnosis,
    QDBookDoctorCellTypeDiagnoisType
} QDBookDoctorCellType;

//单选按钮的值
typedef enum : NSUInteger {
    QDRadioButtonTypeYES = 1,
    QDRadioButtonTypeNO,
} QDRadioButtonType;


@interface QDBookDoctorController ()<UITableViewDataSource,UITableViewDelegate,QDBookDoctorRadioCellDelegate>

@property(nonatomic,weak)UITableView* bookDetailList;
@property(nonatomic,strong)NSIndexPath* hasDiagnostIndex;
@property(nonatomic,weak)UIButton* applyButton;
@property(nonatomic,weak)UILabel* doctorCountLabel;
@property(nonatomic,weak)UILabel* totalLabel;
@property(nonatomic,weak)UIImageView* iconImageView;
@property(nonatomic,weak)UIView* footView;
@end

@implementation QDBookDoctorController

static NSString* normalCellIdentifier = @"normal";
static NSString* radioCellIdentifier = @"radio";



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


- (instancetype)init{
    
    if(self = [super init]){
        _model = [QDBookDoctorModel new];
    }
    return self;
}


- (void)setupUI{
    
    self.navigationItem.title = @"预约就诊";
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    //设置tableView
    [self setupTableView];
    
    [self setupFooterView];
    
    [self setFootApplyButton];
}



/**
 设置顶部疾病类型

 @return 返回头部视图
 */
- (UIView*)setupTableHeaderView{
    
    UIView* headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    
    NSString* sicknessTypeStr = nil;
    
    switch (self.model.ci1_id) {
        case SicknessTypeTumour:
            
            sicknessTypeStr = @"肿瘤";
            
            break;
            
        case SicknessTypeBlood:
            
            sicknessTypeStr = @"血液";
            
            break;
        case SicknessTypeHeartBlood:
            
            sicknessTypeStr = @"心血";
            
            break;
        case SicknessTypeNeurology:
            
            sicknessTypeStr = @"神经";
            
            break;
        case SicknessTypeBone:
            
            sicknessTypeStr = @"骨科";
            
            break;
    }
    
    
    UILabel* sicknessTypeLabel = [UILabel cz_labelWithText:[NSString stringWithFormat:@"疾病类型:%@科",sicknessTypeStr] fontSize:18 color:[UIColor lightGrayColor]];
    
    [headerView addSubview:sicknessTypeLabel];
    
    [sicknessTypeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(16);
        make.centerY.equalTo(headerView);
    }];
    
    
    return headerView;
}


/**
 设置申请按钮
 */
- (void)setFootApplyButton{
    
    CGFloat margin = 8;
    
    UIButton* applyButton = [[UIButton alloc]init];
    [self.view addSubview:applyButton];
    [applyButton setTitle:@"申请预约" forState:UIControlStateNormal];
    [applyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [applyButton setBackgroundColor:[UIColor cz_colorWithRed:128 green:128 blue:128]];
    
    [applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.offset(self.view.bounds.size.width - 4* margin);
        make.top.equalTo(_footView.mas_bottom).offset(margin);
        make.bottom.equalTo(self.view).offset(-2 * margin);
    }];
    
    
    [applyButton addTarget:self action:@selector(sendBook:) forControlEvents:UIControlEventTouchUpInside];
    
    //    applyButton.enabled = NO;
    applyButton.layer.cornerRadius = 10;
    applyButton.layer.masksToBounds = YES;
    
    _applyButton = applyButton;
}

/**
 设置底部视图

 @return 视图
 */
- (UIView*)setupFooterView{
    
    UIView* footerView = [[UIView alloc]init];
    
    _footView = footerView;
    [self.view addSubview:footerView];
    
    CGFloat height = [UIScreen mainScreen].bounds.size.height / 4;
    
    [footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(_bookDetailList.mas_bottom).offset(50);
        make.height.offset(height);
    }];
    
    CGFloat margin = 12;
    
    
    
    UILabel* totalLabel = [UILabel cz_labelWithText:@"一共为你匹配到" fontSize:16 color:[UIColor lightGrayColor]];
    [footerView addSubview:totalLabel];
    [totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footerView);
        make.top.equalTo(footerView);
    }];
    
    
    //医生数量
    UILabel* doctorCountLabel = [UILabel cz_labelWithText:@"24位医生" fontSize:20 color:PPColor];
    
    [footerView addSubview:doctorCountLabel];
    [doctorCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(footerView);
        make.top.equalTo(totalLabel.mas_bottom).offset(margin);
    }];
    
    //图片
    UIImageView* iconImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"doctorCount"]];
    [footerView addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(doctorCountLabel.mas_bottom).offset(margin);
        make.centerX.equalTo(footerView);
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    
    doctorCountLabel.hidden = YES;
    totalLabel.hidden = YES;
    iconImageView.hidden = YES;
    
    
    _doctorCountLabel = doctorCountLabel;
    _totalLabel = totalLabel;
    _iconImageView = iconImageView;
    
    return footerView;
}



#pragma -mark 跳转到医生列表
- (void)sendBook:(UIButton*)sender{
    
    NSLog(@"apply");
    
    UIStoryboard* sb = [UIStoryboard storyboardWithName:@"DoctorApply" bundle:nil];
    
    QDDoctorApplyController* vc = [sb instantiateViewControllerWithIdentifier:@"DoctorApply"];
    vc.parameters = @{@"naviType":@1};
    
    [self.navigationController pushViewController:vc animated:YES];
}



/**
 设置tableView的属性
 */
- (void)setupTableView{
    
    UITableView* bookDetailList = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    bookDetailList.backgroundColor = [UIColor clearColor];
    _bookDetailList = bookDetailList;
    [self.view addSubview:bookDetailList];
    
//    bookDetailList.backgroundColor = [UIColor redColor];
    
    bookDetailList.tableFooterView = [UIView new];
    bookDetailList.scrollEnabled  = NO;
    
    [bookDetailList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(self.view);
        
    }];
    
    bookDetailList.dataSource = self;
    bookDetailList.delegate = self;
    
    [bookDetailList registerClass:[QDBookDoctorRadioCell class] forCellReuseIdentifier:radioCellIdentifier];
    
    [bookDetailList registerClass:[QDBookDoctorNormalCell class] forCellReuseIdentifier:normalCellIdentifier];
    
    
    //设置tableView头部底部视图
    UIView * headerView = [self setupTableHeaderView];
    headerView.frame = CGRectMake(0, 0, 0, 50);
    
    
    
    
    bookDetailList.tableHeaderView = headerView;
    
    
  
    
}


#pragma -mark 设置组间距离
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 7;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 7;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}




#pragma -mark 点击跳转

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == QDBookDoctorCellTypeSickness){
        
        
        //回传选择的疾病类型
        
        QDSelectSicknessController* vc = [[QDSelectSicknessController alloc]init];
        
        vc.cid = self.model.ci1_id;

        vc.callBackBlock = ^(NSUInteger ci2_id,NSUInteger ci3_id,NSString* sicknessName) {
            
            self.model.ci3_id = ci3_id;
            self.model.ci2_id = ci2_id;
            
            QDBookDoctorNormalCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            
            cell.dataDict = @{@"title":sicknessName};
            
            [self setApplyButtonEnable];
        };
        
        [self.navigationController pushViewController:vc animated:YES];
    }

    //选择并发症
    if(indexPath.section == QDBookDoctorCellTypeComplication){
        
        [self loadComplicationData:indexPath];
        
    }
    
    
    //选择曾经的医疗手段
    if(indexPath.section == QDBookDoctorCellTypeDiagnoisType){
        
        
        //回传曾经的治疗手段
        QDSelectDiagnosisController* vc = [[QDSelectDiagnosisController alloc]init];
        
        vc.callBackBlock = ^(NSUInteger diagnosisType,NSString* diagnosisName) {
            
            QDBookDoctorNormalCell* cell = [tableView cellForRowAtIndexPath:indexPath];
            
            cell.dataDict = @{@"title":diagnosisName};
            
            self.model.diagnosis_type = diagnosisType;
        
            
            //设置预约按钮效果
            [self setApplyButtonEnable];
        };
        
        [self.navigationController pushViewController:vc animated:YES];
   
    }
}


#pragma -mark radioCell的代理方法


- (void)radioCell:(QDBookDoctorRadioCell *)cell withSelectIndex:(NSUInteger)index{
    
    ConfirmType type = cell.confirmType;
    
    switch (type) {
        case ConfirmTypeIsRealSick:
            self.model.is_confirmed = index;
            break;
        case ConfirmTypeHasdiagnosis:
            
            self.model.has_diagnosis = index;
            
            
            if(index == QDRadioButtonTypeNO){
                self.model.diagnosis_type = 0;
            }
            
            //根据是否存在治疗史设置隐藏
            UITableViewCell* cell = [_bookDetailList cellForRowAtIndexPath:_hasDiagnostIndex];
            
            if(self.model.ci2_id == 0){
                [QDBannerTools pp_BannerErrorTitle:@"请选择疾病类型!" andTime:1];
                return;
            }
            
          
            
            //设置预约按钮效果
            [self setApplyButtonEnable];
            
            
            CGFloat alpha = index == QDRadioButtonTypeNO ? 0 : 1;
            
            if(index == QDRadioButtonTypeYES){
                
                cell.hidden = NO;
                [UIView animateWithDuration:0.2 animations:^{
                    cell.alpha = alpha;
                } ];
 
            }else{
                
                [UIView animateWithDuration:0.2 animations:^{
                    cell.alpha = alpha;
                } completion:^(BOOL finished) {
                    cell.hidden = YES;
                }];
                
            }
    
            break;
    }
 
    
    NSLog(@"%@",self.model);
}



#pragma -makr 设置申请预约按钮是否可以点击

/**
 设置预约按钮可以否点击
 */
- (void)setApplyButtonEnable{
    
    if(self.model.ci2_id != 0){
        
        //不存在治疗史
        if(self.model.has_diagnosis == 2){
            
            //加载可预约医生
            [self loadDoctorCountInfo];
            _applyButton.userInteractionEnabled = YES;
            _applyButton.enabled = YES;
            [_applyButton setBackgroundColor:PPColor];
            
        //存在治疗史,也选择了治疗方式
        }else if(self.model.has_diagnosis == 1 && self.model.diagnosis_type != 0){
            _applyButton.userInteractionEnabled = YES;
            _applyButton.enabled = YES;
            [_applyButton setBackgroundColor:PPColor];
        }
        else{
            [self applyButtonDisable];
        }
     
    }else{
        [self applyButtonDisable];
    }
}

- (void)applyButtonDisable{
    _applyButton.enabled = NO;
    [_applyButton setBackgroundColor:[UIColor cz_colorWithRed:128 green:128 blue:128]];
}


#pragma -mark 设置cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //选择疾病类型
    if(indexPath.section == 0){
       QDBookDoctorNormalCell* cell = [tableView dequeueReusableCellWithIdentifier:normalCellIdentifier forIndexPath:indexPath];
        return cell;
    }
    
    //选择并发症
    if(indexPath.section == 1){
        QDBookDoctorNormalCell* cell = [tableView dequeueReusableCellWithIdentifier:normalCellIdentifier forIndexPath:indexPath];
        cell.dataDict = @{@"title":@"请选择并发症(多选):"};
        return cell;
    }
    
    //是否确诊
    if(indexPath.section == 2){
        QDBookDoctorRadioCell* cell = [tableView dequeueReusableCellWithIdentifier:radioCellIdentifier forIndexPath:indexPath];
        cell.confirmType = ConfirmTypeIsRealSick;
        cell.dataDict = @{@"title":@"是否已确诊",@"confirm":@[@" 确诊",@" 疑似"]};
        cell.delegate = self;
        return cell;
    }
    
    //是否有医疗史
    if(indexPath.section == 3){
        QDBookDoctorRadioCell* cell = [tableView dequeueReusableCellWithIdentifier:radioCellIdentifier forIndexPath:indexPath];
        cell.confirmType = ConfirmTypeHasdiagnosis;
        cell.dataDict = @{@"title":@"是否存在医疗史:",@"confirm":@[@" 存在",@" 没有"]};
        cell.delegate = self;
        return cell;
    }
    
    //选择曾经的治疗方式
    QDBookDoctorNormalCell* cell = [tableView dequeueReusableCellWithIdentifier:normalCellIdentifier forIndexPath:indexPath];
    cell.dataDict = @{@"title":@"曾经的治疗方式"};
    cell.hidden = YES;
    cell.alpha = 0;
    _hasDiagnostIndex = indexPath;
    return cell;
}

#pragma -mark 点击进入选择并发症
- (void)loadComplicationData:(NSIndexPath*)indexPath{
    
    if(self.model.ci2_id == 0){
        [QDBannerTools pp_BannerErrorTitle:@"请选择疾病类型!" andTime:1];
    }else{
        
        
        QDSelectComlicationController* vc = [[QDSelectComlicationController alloc]init];
        
        vc.ci1_id = self.model.ci1_id;
        vc.ci2_id = self.model.ci2_id;
        
        QDBookDoctorNormalCell* cell = [_bookDetailList cellForRowAtIndexPath:indexPath];
        
        vc.callBackBlock = ^(NSMutableArray* complicationsData) {
            
            NSLog(@"%@",complicationsData);
            
            
            if(complicationsData.count>0){
                [cell resetCell];
               cell.complicationsData = complicationsData;
            }else{
                [cell resetCell];
                [cell setupUI];
            }
            
        };

        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma -mark 加载可预约医生数量

- (void)loadDoctorCountInfo{
    
    NSString* urlString = @"http://iosapi.itcast.cn/doctor/matchedDoctorCount.json.php";
    
    QDNetworkTool* tool = [QDNetworkTool sharedTool];
    
    NSDictionary *postParams = @{@"ci1_id":@(self.model.ci1_id),@"ci2_id":@(self.model.ci2_id),@"ci3_id":@(self.model.ci3_id),@"diagnosis_type":@(self.model.diagnosis_type),@"is_confirmed":@(self.model.is_confirmed),@"user_id":@1000089, @"has_diagnosis":@(self.model.has_diagnosis)};

    
    NSLog(@"params = %@",postParams);
    
    
    tool.requestSerializer = [AFJSONRequestSerializer serializer];
    [tool requestWithHTTPMethod:@"POST" URLString:urlString parameters:postParams CallBack:^(id responseObj) {
        
        if(responseObj != nil){
            
            NSString* result = responseObj[@"msg"]; //FAIL
            
            if([result isEqualToString:@"OK"]){
                
                NSDictionary* dict = responseObj[@"data"];
                
                NSUInteger doctorCount = [dict[@"doctor_count"] integerValue];
                
                [self showDoctorCount:doctorCount];
                
            }else{
                NSLog(@"请求参数错误");
            }
            
        }else{
            NSLog(@"网络请求错误");
        }
    }];
    
}

#pragma -mark 显示预约医生数量

- (void)showDoctorCount:(NSUInteger)count{
    
    _doctorCountLabel.hidden = NO;
    _totalLabel.hidden = NO;
    _iconImageView.hidden = NO;
    
    
    _doctorCountLabel.text = [NSString stringWithFormat:@"%zd位医生",count];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
